package com.zhongke.cotrun.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zhongke.cotrun.common.util.APIResponse;
import com.zhongke.cotrun.model.pojo.AgentInfo;
import com.zhongke.cotrun.model.pojo.AgentJobs;
import com.zhongke.cotrun.model.pojo.ExpertInfo;
import com.zhongke.cotrun.model.pojo.NeedInfo;
import com.zhongke.cotrun.model.pojo.ProjectInfo;
import com.zhongke.cotrun.model.resultpackage.CodeMsg;
import com.zhongke.cotrun.model.validator.UserValidator;
import com.zhongke.cotrun.service.AgentInfoService;
import com.zhongke.cotrun.service.AgentJobsService;
import com.zhongke.cotrun.service.CommonConfigService;
import com.zhongke.cotrun.service.ExpertInfoService;
import com.zhongke.cotrun.service.NeedInfoService;
import com.zhongke.cotrun.service.ProjectInfoService;
import com.zhongke.cotrun.shiro.sys.shiro.ShiroUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

 /**
 * @Description: 经纪人关联工作信息
 * @Author: songjing
 * @Date:   2020-03-28
 * @Version: V1.0
 */
@Api(tags = "经纪人关联工作信息管理")
@RestController
@RequestMapping("/agentJobs")
@Validated
public class AgentJobsController {
	@Autowired
	private AgentInfoService agentInfoService;	
	@Autowired
	private AgentJobsService agentJobsService;	
	@Autowired
	private ProjectInfoService projectInfoService;
	@Autowired
	private ExpertInfoService expertInfoService;
	@Autowired
	private NeedInfoService needInfoService;
	@Autowired
	CommonConfigService commonConfigService;
	/**
	 * 经纪人关联工作
	 * @param agentInfoId 经纪人信息主键
	 * @param mainId 工作主键
	 * @param type 工作类型
	 * @return
	 */
	@ApiOperation(value = "经纪人关联工作")
	@GetMapping(value = "/add")
	public APIResponse add(@NotNull(message = "经纪人主键不能为空") Long agentInfoId,
			@NotNull(message = "工作主键不能为空") Long mainId,@RequestParam(defaultValue = "0") String type) {
		if(ShiroUtils.getWebUserId() == null)
			return APIResponse.returnFail(CodeMsg.ACCOUNT_ERROR);	
		
		//验证经纪人状态为审核通过
		AgentInfo agentInfo = agentInfoService.getById(agentInfoId);
		if(agentInfo == null || !"1".equals(agentInfo.getState()))
			return APIResponse.returnFail(CodeMsg.USER_TYPE_ERROR);	
		
		int jobs = agentJobsService.countAll(agentInfoId,null, mainId, type, "1");
		if(jobs >0)
			return APIResponse.returnFail(CodeMsg.ADD_ERROR);	
		if("0".equals(type))
		{
			//若类型为项目，则项目必须存在，且状态为正常，审核状态为通过
			ProjectInfo projectInfo = projectInfoService.selectByPrimaryKey(mainId.intValue());
			if(projectInfo == null || projectInfo.getState() != 0 || projectInfo.getApprovalState() != 1)
				return APIResponse.returnFail(CodeMsg.DATA_EMPTY);	
		}else if("1".equals(type))
		{
			//若类型为专家，则专家必须存在，且状态为正常，审核状态为通过			
			ExpertInfo e = expertInfoService.selectMyExpertInfo(mainId.intValue());
			if(e == null || e.getState() != 0 || e.getAuditStatus() != 1)
				return APIResponse.returnFail(CodeMsg.DATA_EMPTY);	
		}
		else if("2".equals(type))
		{
			//若类型为需求，则需求必须存在，且状态为正常，审核状态为通过
			NeedInfo needInfo = needInfoService.selectDetailById(mainId);
			if(needInfo == null || !"1".equals(needInfo.getState()))
				return APIResponse.returnFail(CodeMsg.DATA_EMPTY);	
		}
		
		AgentJobs ajob = new AgentJobs();
		ajob.setAgentInfoId(agentInfo.getId());
		ajob.setUserInfoId(agentInfo.getUserInfoId());
		ajob.setMainId(mainId);
		ajob.setType(type);
		ajob.setState("1");
		
		ajob.setCreateBy(ShiroUtils.getWebUserId());
		ajob.setCreateDate(new Date());
		agentJobsService.save(ajob);		
		return APIResponse.returnSuccess("关联经纪人成功");
	}
	
	/**
	  *  经纪人更换停止
	 * @param agentJobs
	 * @return
	 */
	@ApiOperation(value = "经纪人更换且停止")
	@PostMapping(value = "/update")
	public APIResponse update(@RequestBody AgentJobs agentJobs) {		
		if(ShiroUtils.getWebUserId() == null)
			return APIResponse.returnFail(CodeMsg.ACCOUNT_ERROR);	
		if(agentJobs == null || StringUtil.isEmpty(agentJobs.getReasonNote()) || agentJobs.getId() == null)
			return APIResponse.returnFail(CodeMsg.BIND_ERROR);
		
		AgentJobs agentJob = agentJobsService.getById(agentJobs.getId());		
		if(agentJob==null || "2".equals(agentJob.getState()) || !agentJob.getCreateBy().equals(ShiroUtils.getWebUserId()))
			return APIResponse.returnFail(CodeMsg.DATA_EMPTY);
		
		int jobs = agentJobsService.countAll(agentJobs.getId(),null, agentJob.getMainId(), agentJob.getType(), "1");
		if(jobs >0)
			return APIResponse.returnFail(CodeMsg.UPDATE_ERROR);	
		
		agentJob.setState("2");
		agentJob.setReasonNote(agentJobs.getReasonNote());
		if(agentJobs.getScore() == null || agentJobs.getScore() == 0)
			agentJob.setScore(5);
		else
			agentJob.setScore(agentJobs.getScore());
		if(StringUtil.isNotEmpty(agentJobs.getAppraise()))
			agentJob.setAppraise(agentJobs.getAppraise());
		if(StringUtil.isNotEmpty(agentJobs.getRecommendNote()))
			agentJob.setRecommendNote(agentJobs.getRecommendNote());
		
		agentJob.setUpdateBy(ShiroUtils.getWebUserId());
		agentJob.setUpdateDate(new Date());
				
		if(agentJobsService.updateById(agentJob))
			return APIResponse.returnSuccess("结束关联成功");
		else
			return APIResponse.returnFail(CodeMsg.SERVER_ERROR);
	}
	
	/**
	  * 分页列表查询
     * @param mainId 工作表主键
     * @param type 工作类型
     * @param state 状态
	 * @param pageNum页码
	 * @param pageSize
	 * @return
	 */
	@ApiOperation(value = "查看本人工作关联列表")
   @GetMapping(value= {"/selectAll"},produces = "application/json;charset=utf-8")
	public APIResponse selectAll(@RequestParam(defaultValue = "0") String type,String state, String searchKey,
			@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
		if(ShiroUtils.getWebUserId() == null)
				return APIResponse.returnFail(CodeMsg.ACCOUNT_ERROR);	
		//PageInfo page = agentJobsService.selectAll(null, 29L, null, type, state,searchKey, pageNum, pageSize);
		PageInfo page = agentJobsService.selectAll(null,ShiroUtils.getWebUserId(),null,type,state,searchKey, pageNum, pageSize);
		List list = page.getList();
		if(list != null && list.size()>0)
		{
			for(int i=0;i<list.size();i++)
			{
				AgentJobs agentJobs = (AgentJobs)list.get(i);
				if("0".equals(agentJobs.getType()))
				{
					ProjectInfo projectInfo = projectInfoService.selectByPrimaryKey(agentJobs.getMainId().intValue());
					agentJobs.setProjectInfo(projectInfo);
				}else if("1".equals(agentJobs.getType()))
				{	
					ExpertInfo e = expertInfoService.selectMyExpertByuId(agentJobs.getMainId().intValue());
					agentJobs.setExpertInfo(e);
				}
				else if("2".equals(agentJobs.getType()))
				{
					NeedInfo needInfo = needInfoService.selectDetailById(agentJobs.getMainId());
					agentJobs.setNeedInfo(needInfo);
				}
			}
		}
		return APIResponse.returnSuccess(page);
	}
	/**
	 * 按工作类型统计本人进行中工作数量
	 * @return
	 */
	@ApiOperation(value = "按工作类型统计本人进行中工作数量")
  @GetMapping(value= {"/countMineByType"},produces = "application/json;charset=utf-8")
	public APIResponse countMineByType() {
		if(ShiroUtils.getWebUserId() == null)
			return APIResponse.returnFail(CodeMsg.ACCOUNT_ERROR);	
		Map map = agentJobsService.countAllByType(null, ShiroUtils.getWebUserId(), null, "1");
		return APIResponse.returnSuccess(map);
	}
	/**
	 * 统计指定人员得分
	 * @return
	 */
	@ApiOperation(value = "统计指定人员得分")
  @GetMapping(value= {"/sumScore"},produces = "application/json;charset=utf-8")
	public APIResponse sumScore() {
	//	if(ShiroUtils.getWebUserId() == null)
	//		return APIResponse.returnFail(CodeMsg.ACCOUNT_ERROR);	
		return APIResponse.returnSuccess(agentJobsService.sumScoreByUser(null, 29L, null, null));
	}
}
